//首先访问后端，拿到文档文件夹列表
const axios=require("axios");
const hljs = require('./highlight/highlight.pack');
require('./css/index.less');
require('./css/md_container.less');
require('./highlight/styles/idea.css')
const $=require('jquery');
const marked=require('marked');
axios.get('/api/getAllTree').then(response=>{
    let allPath=response.data;
    for(let p of allPath){
        createTreeNode(p,$("#tree_container"));
    }
});

function createTreeNode(node,$parent){
    let $li=$('<li></li>');
    let $span=$(`<span>${node.name}</span>`)
    if(node.type==='file'){
        $span.addClass('side_file');
        $span.data('raw',node)
    }
    else $span.addClass('side_dir');
    $li.append($span);
    $parent.append($li);
    if(node.type==='dir'){
        if(node.type==='dir' && node.children && node.children.length>0){
            let $ul=$('<ul></ul>')
            $li.append($ul)
            for(let nc of node.children){
                createTreeNode(nc,$ul);
            }
        }
    }
}
$('#tree_container').on('click','.side_file',function(){
    let $this=$(this);
    let data=$this.data('raw');
    let targetPath=data.path;
    load_md_content(targetPath)
});

function load_md_content(targetPath){
    axios.post('/api/loadmd',{path:targetPath}).then(response=>{
        let content=response.data;
        let h=marked( content )
        $('#md_content').html(h)
        let $code=$('code');
        for(let i=0;i<$code.length;i++){
            
            let $codeEle=$($code[i]);
            let c=$codeEle.text()
            c=hljs.highlightAuto(c).value;
            $codeEle.html(c);
        }
    });
}